//
//  FFRedPacketsRecordVC.m
//  LiMaoRedPackets
//
//  Created by JayLuo on 2020/8/22.
//

#import "FFRedPacketsRecordVC.h"
#import "Masonry.h"
#import "ReactiveObjC.h"
#import "FFRedPacketsRecordCell.h"
#import "FFRedPacketsRecordModel.h"
#import "MJExtension.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface FFRedPacketsRecordVC ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, weak) UILabel *nameLabel;
@property(nonatomic, weak) UILabel *redPacketTips;
@property(nonatomic, weak) UILabel *redPacketInfo;
@property(nonatomic, weak) UILabel *redPacketInfo24hTips;
@property(nonatomic, weak) UILabel *moneyLabel;
@property(nonatomic, weak)  UIImageView *avatarImageView;
@property(nonatomic, weak)  UIButton *walletButton;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) FFRedPacketsRecordModel *model;
@end

@implementation FFRedPacketsRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupHeader];
    [self setupBody];
}

- (void)setRedpacket_no:(NSString *)redpacket_no {
    _redpacket_no = redpacket_no;
    [self requestData];
}

- (void)requestData {
     __weak typeof(self) weakSelf = self;
    // 红包详情
    [[WKAPIClient sharedClient] GET:[NSString stringWithFormat:@"redpackets/%@",  _redpacket_no] parameters:@{}].then(^(NSDictionary *dict){

        [FFRedPacketsRecordModel mj_setupObjectClassInArray:^NSDictionary *{
            return @{
                        @"records" : [FFRedPacketsRecord class],
                    };
        }];

        FFRedPacketsRecordModel *model = [FFRedPacketsRecordModel mj_objectWithKeyValues:dict];
        
        weakSelf.model = model;
        
        // 自己
        if (weakSelf.redPacketsRecordType == RedPacketsRecordTypeP2P) {
            if ([model.sender_uid isEqualToString:[WKApp shared].loginInfo.uid]) {
                weakSelf.moneyLabel.text = [NSString stringWithFormat:@"%.2f", (double)model.amount/100.0];
                weakSelf.walletButton.hidden = YES;
                
                if (model.status == 3) {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元",weakSelf), model.total_num, (double)model.amount/100.0];
                    weakSelf.redPacketInfo24hTips.hidden = YES;
                } else if (model.status == 4) {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元,红包已过期", weakSelf), model.total_num, (double)model.amount/100.0];
                    weakSelf.redPacketInfo24hTips.hidden = YES;
                }else {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"红包金额%.2f元, 等待对方领取", weakSelf), (double)model.amount/100.0];
                    weakSelf.redPacketInfo24hTips.hidden = NO;
                }
                
            }else {
                if (model.status == 4) {
                    weakSelf.moneyLabel.text = [NSString stringWithFormat:@"%.2f", (double)model.my_open_amount/100.0];
                    weakSelf.walletButton.hidden = YES;
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元,红包已过期", weakSelf), (long)model.total_num, (double)model.amount/100.0];
                }else {
                    weakSelf.moneyLabel.text = [NSString stringWithFormat:@"%.2f", (double)model.my_open_amount/100.0];
                    weakSelf.walletButton.hidden = NO;
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元", weakSelf), (long)model.total_num, (double)model.amount/100.0];
                }
                
            }
        }else {
            weakSelf.moneyLabel.text = [NSString stringWithFormat:@"%.2f", (double)model.my_open_amount/100.0];
            weakSelf.walletButton.hidden = NO;
            if ([model.sender_uid isEqualToString:[WKApp shared].loginInfo.uid]) {
                if (model.status == 3) {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元,%@被抢光了", weakSelf), (long)model.total_num, (double)model.amount/100.0, [self convertSecond2HMS:model.finished_spend]];
                    weakSelf.redPacketInfo24hTips.hidden = YES;
                } else if (model.status == 4) {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元,红包已过期", weakSelf), (long)model.total_num, (double)model.amount/100.0];
                    weakSelf.redPacketInfo24hTips.hidden = YES;
                }else {
                    
                    if (model.open_num == model.total_num) {
                        weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包共%.2f元,%@被抢光了", weakSelf), (long)model.total_num, (double)model.amount/100.0, [self convertSecond2HMS:model.finished_spend]];
                        weakSelf.redPacketInfo24hTips.hidden = YES;
                    }else {
                        weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"已领取%ld/%ld个,共%.2f/%.2f元", weakSelf),(long)model.open_num, model.total_num,  (double)model.balance/100.0, (double)model.amount/100.0];
                        weakSelf.redPacketInfo24hTips.hidden = NO;
                    }
                    
                }
            }else {
                if (model.status == 3) {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包,%@被抢光了", weakSelf), (long)model.total_num, [self convertSecond2HMS:model.finished_spend]];
                    weakSelf.redPacketInfo24hTips.hidden = YES;
                } else if (model.status == 4) {
                    weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包,红包已过期", weakSelf), (long)model.total_num];
                    weakSelf.redPacketInfo24hTips.hidden = YES;
                }else {
                    if (model.open_num == model.total_num) {
                        weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"%ld个红包,%@被抢光了", weakSelf), (long)model.total_num,[self convertSecond2HMS:model.finished_spend]];
                        weakSelf.redPacketInfo24hTips.hidden = YES;
                    }else {
                        weakSelf.redPacketInfo.text = [NSString stringWithFormat:LLangW(@"领取%ld/%ld个", weakSelf),(long)model.open_num, model.total_num];
                        weakSelf.redPacketInfo24hTips.hidden = YES;
                    }
                    
                    
                }
            }
 
        }
        
        weakSelf.nameLabel.text = [NSString stringWithFormat:LLangW(@"%@的红包", weakSelf), model.sender_name];
        weakSelf.redPacketTips.text = model.blessing?:LLangW(@"恭喜发财, 大吉大利", weakSelf);
        
        
        NSString *avatarString = [WKAvatarUtil getAvatar:model.sender_uid];
        [weakSelf.avatarImageView setImageWithURL:[NSURL URLWithString:avatarString] placeholderImage:[WKApp shared].config.defaultAvatar];
        [weakSelf.tableView reloadData];

        
    }).catch(^(NSError *error){
        
    });
}

- (void)setupHeader {
    self.title = @"";
    self.navigationBar.showBackButton = NO;
    __weak typeof(self) weakSelf = self;
    self.navigationBar.onBack = ^{
        [weakSelf close];
    };
   
    self.navigationBar.style = WKNavigationBarStyleWhite;
//    self.navigationBar.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationBar.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0];
    });
    
    UIButton *closeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [closeButton setTitle:LLang(@"关闭") forState:(UIControlStateNormal)];
    @weakify(self);
    [[closeButton rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self close];
    }];
    [self.view addSubview:closeButton];
    CGFloat statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.top.equalTo(self.view).offset(statusHeight + 5);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
}

- (void)setupBody {
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, - 1000, self.view.frame.size.width, 1000)];
    bgView.layer.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0].CGColor;
    [self.tableView addSubview:bgView];
    
    self.view.backgroundColor = [WKApp shared].config.backgroundColor;
    
    UIView *headView = [[UIView alloc] init];
    headView.frame = CGRectMake(0,0,SCREEN_WIDTH,300);
    headView.backgroundColor =[WKApp shared].config.backgroundColor;
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0,0,SCREEN_WIDTH,80);
    view.layer.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0].CGColor;
    [headView addSubview:view];
    
    self.tableView.tableHeaderView = headView;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(SCREEN_WIDTH/2, SCREEN_WIDTH*2 - 40 + 80) radius:SCREEN_WIDTH*2 startAngle:0 endAngle:M_PI clockwise:NO];
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.lineWidth = 10;
    pathLayer.strokeColor = [UIColor colorWithRed:230/255.0 green:204/255.0 blue:204/255.0 alpha:1.0].CGColor;
    pathLayer.path = path.CGPath;
    pathLayer.fillColor = [WKApp shared].config.backgroundColor.CGColor;
    [view.layer addSublayer:pathLayer];
    view.layer.masksToBounds = YES;
    
    UIView *contanerView = [[UIView alloc] init];
    contanerView.frame = CGRectMake(0,0 + 30,[UIScreen mainScreen].bounds.size.width,50);
    contanerView.layer.backgroundColor = [UIColor clearColor].CGColor;
    [headView addSubview:contanerView];
    
    [contanerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_bottom);
        make.width.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = @"--的红包";
    nameLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    [contanerView addSubview:nameLabel];
    _nameLabel = nameLabel;
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
         make.centerY.equalTo(contanerView.mas_centerY);
         make.centerX.equalTo(contanerView.mas_centerX).offset(15);
    }];
    
    
    UIImage *avatarImage = [self imageName:@"avatar_male"];
    UIImageView *avatarImageView = [[UIImageView alloc] initWithImage:avatarImage];
    [contanerView addSubview:avatarImageView];
    avatarImageView.layer.cornerRadius = 15;
    avatarImageView.layer.masksToBounds = YES;
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(nameLabel.mas_left).mas_offset(-5);
        make.centerY.equalTo(contanerView.mas_centerY);
        make.width.height.equalTo(@30);
    }];
    
    _avatarImageView = avatarImageView;
    
    UILabel *redPacketTips = [[UILabel alloc] init];
    redPacketTips.text = LLang(@"恭喜发财，大吉大利");
    redPacketTips.font = [UIFont systemFontOfSize:12];
    redPacketTips.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
    redPacketTips.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:redPacketTips];
    _redPacketTips = redPacketTips;
    [redPacketTips mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(contanerView.mas_bottom).offset(5);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    UILabel *moneyLabel = [[UILabel alloc] init];
    moneyLabel.text = @"--";
    moneyLabel.font = [UIFont fontWithName:@"AvenirNext-Medium" size:45];
    moneyLabel.textColor = [UIColor colorWithRed:198/255.0 green:126/255.0 blue:33/255.0 alpha:1.000000];
    [headView addSubview:moneyLabel];
    _moneyLabel = moneyLabel;
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(redPacketTips.mas_bottom).offset(23);
        make.centerX.equalTo(self.view.mas_centerX).offset(-10);
    }];
    
    UILabel *moneySymbolLabel = [[UILabel alloc] init];
    moneySymbolLabel.text = @"元";
    moneySymbolLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
    moneySymbolLabel.textColor = [UIColor colorWithRed:198/255.0 green:126/255.0 blue:33/255.0 alpha:1.000000];
    [headView addSubview:moneySymbolLabel];
    [moneySymbolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(moneyLabel.mas_right);
        make.centerY.equalTo(moneyLabel.mas_centerY).offset(8);
    }];
    
    UIButton *walletButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [walletButton setTitle:LLang(@"已存入钱包 >") forState:(UIControlStateNormal)];
    walletButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [walletButton setTitleColor:[UIColor colorWithRed:198/255.0 green:126/255.0 blue:33/255.0 alpha:1.000000] forState:(UIControlStateNormal)];
    [headView addSubview:walletButton];
    [walletButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(moneyLabel.mas_bottom);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    _walletButton = walletButton;
    
    @weakify(self);
    [[walletButton rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
         @strongify(self);
        [self dismissViewControllerAnimated:NO completion:^{
            [[WKApp shared] invoke:@"goWallet" param:nil];
        }];
    }];
    
    if (self.redPacketsRecordType == RedPacketsRecordTypeGroup || self.redPacketsRecordType == RedPacketsRecordTypeP2P) {
        
        // 群聊列表
        UILabel *redPacketTips = [[UILabel alloc] init];
        redPacketTips.text = LLang(@"--个红包共--元");
        redPacketTips.font = [UIFont systemFontOfSize:12];
        redPacketTips.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
        redPacketTips.textAlignment = NSTextAlignmentLeft;
        [headView addSubview:redPacketTips];
        _redPacketInfo = redPacketTips;
        [redPacketTips mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(walletButton.mas_bottom).offset(10);
            make.left.equalTo(self.view).offset(15);
        }];
        
        
        // 群聊列表
        UILabel *redPacketTips2 = [[UILabel alloc] init];
        redPacketTips2.text = LLang(@"未领取的红包, 将于24小时后发起退款");
        redPacketTips2.font = [UIFont systemFontOfSize:12];
        redPacketTips2.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
        redPacketTips2.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:redPacketTips2];
        redPacketTips2.hidden = YES;
        _redPacketInfo24hTips = redPacketTips2;
        [redPacketTips2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-50);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
        
    }
}

#pragma mark - lazy
- (UITableView *)tableView {
    if(!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        UIEdgeInsets separatorInset   = _tableView.separatorInset;
        separatorInset.right          = 0;
        _tableView.separatorInset = separatorInset;
        _tableView.backgroundColor=[UIColor clearColor];
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.estimatedRowHeight = 50;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.sectionHeaderHeight =0.0f;
        _tableView.sectionFooterHeight =0.0f;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.decelerationRate = 0.1;
        [_tableView registerClass:FFRedPacketsRecordCell.class forCellReuseIdentifier:[FFRedPacketsRecordCell cellId]];
        
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.model.records.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FFRedPacketsRecordCell *cell =  [tableView dequeueReusableCellWithIdentifier:[FFRedPacketsRecordCell cellId]];
    [cell refreshWithModel:self.model.records[indexPath.row] type:(LIMRedPacketsRecordList)];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FFRedPacketsRecord *record = self.model.records[indexPath.row];
    [[WKApp shared]  invoke:WKPOINT_USER_INFO param:@{
        @"uid":record.uid?:@"",
    }];
}


- (NSString *)convertSecond2HMS:(NSInteger)seconds {
    
    if (seconds >= 60 * 60) { //  时分秒
        NSInteger second = seconds % 60;
        NSInteger minute = (seconds / 60) % 60;
        NSInteger hour = seconds / 3600;
        return [NSString stringWithFormat:LLang(@"%ld小时%ld分%ld秒"), hour, minute, second];
    }else if (seconds >= 60) { // 分
        NSInteger second = seconds % 60;
        NSInteger minute = (seconds / 60) % 60;
        return [NSString stringWithFormat:LLang(@"%ld分%ld秒"), minute, second];
    }else { // 秒
        return [NSString stringWithFormat:LLang(@"%ld秒"), seconds];
    }
    
}


- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

- (void)close {
    [[WKNavigationManager shared] popViewControllerAnimated:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIImage*)imageName:(NSString*)name {
    return [[WKApp shared] loadImage:name moduleID:@"LiMaoRedPackets"];
}
@end
